package com.kpx.app.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ServiceException;
import com.kpx.app.R;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.AddressBean;
import com.kpx.app.bean.LoginUser;
import com.kpx.app.bean.UploadBean;
import com.kpx.app.bean.User;
import com.kpx.app.configs.Constants;
import com.kpx.app.listener.AliyunUploadListener;
import com.kpx.app.utils.AliyunFileUploader;
import com.kpx.app.utils.ImageLoader;
import com.kpx.app.utils.ImageUtils;
import com.kpx.app.utils.ImagesBulkUpload;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.StringUtil;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.datautils.FileUtils;
import com.kpx.app.utils.datautils.LogUtils;
import com.kpx.app.utils.encrypt.BitmapHelper;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;
import com.kpx.app.view.ViewComItem;
import com.kpx.app.wigdet.BottomUpDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.PhotoPreviewActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by congdy on 17/3/4.
 */
@RuntimePermissions
public class ActivityUserInfo extends ActivityBase implements ImageUtils.SelectImageListener {
    @BindView(R.id.titleview)
    TitleView titleview;
    @BindView(R.id.img_hide)
    ImageView imgHide;
    @BindView(R.id.ll_show_mention)
    LinearLayout llShowMention;
    @BindView(R.id.img_user_icon)
    ImageView imgUserIcon;
    @BindView(R.id.ll_show_icon)
    LinearLayout llShowIcon;
    @BindView(R.id.ll_userinfo_content)
    LinearLayout ll_userinfo_content;
    public static final int TYPE_NICK = 0;//昵称
    public static final int TYPE_SEX = 1;//性别
    public static final int TYPE_LOCATION = 2;//地区
    public static final int TYPE_AGE = 3;//年龄
    public static final int TYPE_HEIGHT = 4;//身高
    public static final int TYPE_WEIGHT = 5;//体重
    public static final int TYPE_SHOSE_SIZE = 6;//鞋码
    public static final int TYPE_CLOTH_SIZE = 7;//衣服尺码
    public static final int TYPE_BWH = 8;//三围
    public static final int TYPE_LABEL = 9;//标签
    public static final int TYPE_ADDRESS = 10;//收获地址
    public static final int TYPE_HEADIMG = 11;//头像

    public static final int TYPE_BWH_X = 12;//三围
    public static final int TYPE_BWH_Y = 13;//三围
    public static final int TYPE_BWH_T = 14;//三围
    public static final int TYPE_BWH_XZ = 15;//三围
    //    private String[] titles = {"昵称", "性别", "地区", "年龄", "身高", "体重", "鞋码", "尺码", "三围", "标签", "收货地址"};
//    private String[] des = {"", "请选择性别", "请选择地区", "请选择年龄", "请选择身高", "请选择体重", "请选择鞋码"
//            , "请选择尺码", "请选择三围", "设置标签", "请设置收货地址"};
    private String[] titles = {"昵称", "性别", "地区", "年龄", "身高", "体重", "鞋码", "尺码", "三围", "标签"};
    private String[] des = {"", "请选择性别", "请选择地区", "请选择年龄", "请选择身高", "请选择体重", "请选择鞋码"
            , "请选择尺码", "请选择三围", "设置标签"};
    /**
     * 从相册选择照片回调
     */
    private final int REQUEST_CODE_CAPTURE = 6;
    /**
     * 拍摄照片回调
     */
    private final int REQUEST_CODE_CALLERY = 7;
    private String headImageCloudKey;

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
        UIUtils.setNormalTitle(titleview, "个人资料");
        addItemViews();
    }

    private void addItemViews() {
        for (int i = 0; i < titles.length; i++) {
            ViewComItem v = new ViewComItem(ActivityUserInfo.this);
            v.setTitleStr(titles[i]);
            v.setTag(i);
            v.setOnClickListener(clicklistener);
            ll_userinfo_content.addView(v);
        }
    }

    @Override
    public void initData() {
        if (UserInfoUtils.isUserLogin()) {
            ImageLoader.loadCircle(this, UserInfoUtils.getCachedLoginUser().getUSER().getHeadImg(), imgUserIcon, R.drawable.default_head_img2);
            for (int i = 0; i < ll_userinfo_content.getChildCount(); i++) {
                if (ll_userinfo_content.getChildAt(i).getTag() != null) {
                    setData(ll_userinfo_content.getChildAt(i));
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void setData(View view) {
        final ViewComItem v = (ViewComItem) view;
        final User user = UserInfoUtils.getCachedLoginUser().getUSER();
        switch ((Integer) view.getTag()) {
            case TYPE_NICK://昵称
                v.setDes(TextUtils.isEmpty(user.getNickName()) ? "" : user.getNickName());
                break;
            case TYPE_SEX://性别
                if (!TextUtils.isEmpty(user.getSex())) {
                    v.setDes(user.getSex().endsWith("1") ? "男" : "女");
                }
                break;
            case TYPE_LOCATION://地区
                v.setDes((TextUtils.isEmpty(user.getRegion()) || user.getRegion() == null) ? "" : user.getRegion());
                break;
            case TYPE_AGE://年龄
                v.setDes((TextUtils.isEmpty(user.getAge()) || user.getAge() == null) ? "" : user.getAge());
                break;
            case TYPE_HEIGHT://身高
                v.setDes((TextUtils.isEmpty(user.getHeight()) || user.getHeight() == null) ? "" : user.getHeight() + "cm");
                break;
            case TYPE_WEIGHT://体重
                v.setDes((TextUtils.isEmpty(user.getWeight()) || user.getWeight() == null) ? "" : user.getWeight() + "kg");
                break;
            case TYPE_SHOSE_SIZE://鞋码
                v.setDes((TextUtils.isEmpty(user.getShoeSize()) || user.getShoeSize() == null) ? "" : user.getShoeSize() + "码");
                break;
            case TYPE_CLOTH_SIZE://衣服尺码
                v.setDes((TextUtils.isEmpty(user.getClothingSize()) || user.getClothingSize() == null) ? "" : user.getClothingSize());
                break;
            case TYPE_BWH://三围
                if (!TextUtils.isEmpty(user.getSex()) || (user.getSex() != null)) {
                    v.setVisibility(user.getSex().endsWith("1") ? View.GONE : View.VISIBLE);
                }
                if ((!TextUtils.isEmpty(user.getSex()) || (user.getSex() != null)) && user.getSex().endsWith("2")) {
                    v.setDes((TextUtils.isEmpty(user.getBust() + user.getWaist() + user.getHips() + user.getCupSize()) || user.getBust() == null) ? "" : user.getBust() + " " + user.getWaist() + " " + user.getHips() + " " + user.getCupSize());
                }
                break;
            case TYPE_LABEL://标签
                v.setSigns((TextUtils.isEmpty(user.getUserselectedTags()) || user.getUserselectedTags() == null) ? "" : user.getUserselectedTags());
                break;
            case TYPE_ADDRESS://收获地址
                UserInfoUtils.getAddress(ActivityUserInfo.this, new UserInfoUtils.OnGetAddressdataBackListener() {
                    @Override
                    public void back(ArrayList<AddressBean> aBeans) {
                        if (aBeans != null && aBeans.size() > 0) {
                            if (aBeans.size() == 1) {
                                v.setDes(aBeans.get(0).getRegion() + aBeans.get(0).getAddress());
                            } else {
                                for (int i = 0; i < aBeans.size(); i++) {
                                    if (aBeans.get(i).getIsDefault() == 1) {
                                        v.setDes(aBeans.get(i).getRegion() + aBeans.get(i).getAddress());
                                    }
                                }
                            }
                        }
                    }
                });
                break;

        }
    }

    private View.OnClickListener clicklistener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (((Integer) v.getTag())) {
                case TYPE_SEX://性别
                    chooseSexType();
                    break;
                case TYPE_NICK://昵称
                case TYPE_LOCATION://地区
                case TYPE_AGE://年龄
                case TYPE_HEIGHT://身高
                case TYPE_WEIGHT://体重
                case TYPE_SHOSE_SIZE://鞋码
                    ActivityUpdateUserinfo.updateType = ((Integer) v.getTag());
                    IntentUtil.gotoActivity(ActivityUserInfo.this, ActivityUpdateUserinfo.class);
                    break;
                case TYPE_CLOTH_SIZE://衣服尺码
                case TYPE_BWH://三围
                    AcitivityUpdateUserInfo2.updateType = ((Integer) v.getTag());
                    IntentUtil.gotoActivity(ActivityUserInfo.this, AcitivityUpdateUserInfo2.class);
                    break;
                case TYPE_LABEL://标签
                    IntentUtil.gotoActivity(ActivityUserInfo.this, ActivityUserinfoSign.class);
                    break;
                case TYPE_ADDRESS://收获地址
                    IntentUtil.gotoActivity(ActivityUserInfo.this, ActivityOrderChoiceAddress.class);
                    break;
            }
        }
    };


    @Override
    public void onReceiver(Context context, Intent intent) {

    }

    @OnClick({R.id.img_hide, R.id.ll_show_icon})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_hide:
                llShowMention.setVisibility(View.GONE);
                break;
            case R.id.ll_show_icon:
                String[] menus ;
                if(TextUtils.isEmpty(UserInfoUtils.getCachedLoginUser().getUSER().getHeadImg())){
                    menus = new String[]{"拍照", "从相册中选择"};
                }else {
                    menus = new String[]{"拍照", "从相册中选择", "查看图片"};
                }
                BottomUpDialog bottomUpDlg = new BottomUpDialog(this, menus, new BottomUpDialog.OnPositionClickListener2() {
                    @Override
                    public void onPositionClick(int position, BottomUpDialog dialog) {
                        switch (position) {
                            case 0:
                                ActivityUserInfoPermissionsDispatcher.getCameraPermissionWithCheck(ActivityUserInfo.this);
                                break;
                            case 1:
                                ImageUtils.openGalleryForResult(ActivityUserInfo.this, REQUEST_CODE_CALLERY);
                                break;
                            case 2:
                                Intent intent = new Intent(ActivityUserInfo.this, PhotoPreviewActivity.class);
                                ArrayList<PhotoInfo> list = new ArrayList<PhotoInfo>();
                                PhotoInfo p = new PhotoInfo();
                                p.setPhotoPath(UserInfoUtils.getCachedLoginUser().getUSER().getHeadImg());
                                Bitmap bitmap = ImageLoader.load(ActivityUserInfo.this, p.getPhotoPath());
                                if (bitmap != null) {
                                    p.setWidth(bitmap.getWidth());
                                    p.setHeight(bitmap.getHeight());
                                }
                                list.add(p);
                                intent.putExtra(PhotoPreviewActivity.PHOTO_LIST, list);
                                startActivity(intent);
                                break;
                        }
                        dialog.dismiss();
                    }
                });
                bottomUpDlg.show();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        dissmissLoadingDialog();
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_CAPTURE:
                    ImageUtils.cropImage(this);
                    break;
                case REQUEST_CODE_CALLERY:
                    if (data == null) {
                        return;
                    }
                    ImageUtils.galleryResultCropImage(this, data.getData(), this);
                    break;
            }
        }
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    public void getCameraPermission() {
        ImageUtils.captureForResult(ActivityUserInfo.this, REQUEST_CODE_CAPTURE);
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    public void showRationaleForCamera(final PermissionRequest request) {
        request.proceed();
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    public void deniedCameraPermission() {
        ToastUtil.getInstance().showDialog(this, getString(R.string.denied_camera_permission));
    }

    /**
     * 选择性别
     */
    private void chooseSexType() {
        final String[] choices = {"男", "女"};
        int selectedItem = 0;
        AlertDialog alertDialog = new AlertDialog.Builder(this).setSingleChoiceItems(choices, selectedItem, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, final int which) {
                showLoadingDialog();
                MyHashMap map = new MyHashMap();
                map.put("sex", (which + 1) + "");
                UserInfoUtils.toUpdateData(ActivityUserInfo.this, map, new UserInfoUtils.OnUpdateUserInfoBackListener() {
                    @Override
                    public void back(boolean issuccess, String msg) {
                        dissmissLoadingDialog();
                        if (issuccess) {
                            UserInfoUtils.updateUserInfoCache(ActivityUserInfo.TYPE_SEX, (which + 1) + "");
                            ToastUtil.getInstance().showToast(ActivityUserInfo.this, "保存成功");
                            initData();
                        }
                    }
                });
                dialog.dismiss();
            }
        }).setTitle("选择性别：").create();
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    @Override
    public void onSelectDone() {
        File tempFile1 = ImageUtils.getCropFile();
        if (null == tempFile1 || !tempFile1.exists()) {
            tempFile1 = new File(FileUtils.getTempCacheDir(), ImageUtils.TEMP_PHOTO_FILE_NAME);
            if (null == tempFile1 || !tempFile1.exists()) {
                ToastUtil.getInstance().showToast(ActivityUserInfo.this, "上传图片失败, 请重试!");
                return;
            }
        }
        final File tempFile = tempFile1;
        new Thread() {
            @Override
            public void run() {
//                String tempPath = BitmapHelper.compressBitmap(tempFile.getPath(), 200, 200);
                String tempPath = tempFile.getPath();
                if (!TextUtils.isEmpty(tempPath)) {
                    Message message = new Message();
                    message.what = 1;
                    message.obj = tempPath;
                    handler.sendMessage(message);
                    return;
                }
                ToastUtil.getInstance().showToast(ActivityUserInfo.this, R.string.image_parse_fail);
            }
        }.start();
    }

    @Override
    public void onSelectFail() {
        ToastUtil.getInstance().showToast(ActivityUserInfo.this, R.string.image_format_fail);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String headImageLocalPath = (String) msg.obj;
            LoginUser loginUser = UserInfoUtils.getCachedLoginUser();
            headImageCloudKey = loginUser.getUSER().getDmId() + "/" + StringUtil.getUniqueString() + Constants.IMAGE_FILE_SUFFIX;
            uploadHeadImage(loginUser, headImageLocalPath);
        }
    };

    private void uploadHeadImage(LoginUser loginUser, String headImageLocalPath) {
        if (TextUtils.isEmpty(headImageCloudKey)) {
            return;
        }
//        try {
//            new AliyunFileUploader(headImageLocalPath, headImageCloudKey, loginUser.getACCOUNTCONFIG().getBucketone(), ActivityUserInfo.this, new AliyunUploadListener() {
//                @Override
//                public void onSuccess(String cloudKey, String sourceFilePath) {
//                    showLoadingDialog();
//                    showLoadingDialog();
//                    MyHashMap map = new MyHashMap();
//                    map.put("headImg", headImageCloudKey);
//                    UserInfoUtils.toUpdateData(ActivityUserInfo.this, map, new UserInfoUtils.OnUpdateUserInfoBackListener() {
//                        @Override
//                        public void back(boolean issuccess, String msg) {
//                            dissmissLoadingDialog();
//                            if (issuccess) {//http://ozzptestimage1.oss-cn-shenzhen.aliyuncs.com//2103021484934144/b0c83dbd66a949f2a5b4368ff7ce84ab6092.jpeg
//                                ToastUtil.getInstance().showToast(ActivityUserInfo.this, "保存成功");
//                                UserInfoUtils.getNetLoginUser(ActivityUserInfo.this, new UserInfoUtils.OnGetNetInfoBack() {
//                                    @Override
//                                    public void back(LoginUser info) {
//                                        initData();
//                                    }
//                                });
//                            }
//                        }
//                    });
//                }
//
//                @Override
//                public void onProgress(String cloudKey, long progress, long total) {
//                }
//
//                @Override
//                public void onFailure(String cloudKey, ServiceException e) {
//                    LogUtils.e("--", "图像上传失败原因：" + e);
//                    ToastUtil.getInstance().showToast(ActivityUserInfo.this, "图像上传失败", Toast.LENGTH_SHORT);
//                }
//            }).upload();
//        } catch (FileNotFoundException e) {
//            LogUtils.e("--", "图像上传失败原因：" + e);
//            ToastUtil.getInstance().showToast(ActivityUserInfo.this, "图像上传失败", Toast.LENGTH_SHORT);
//        }
        List<UploadBean> tem = new ArrayList<>();
        UploadBean u = new UploadBean();
        u.setCloudKey(headImageCloudKey);
        u.setLocalPath(headImageLocalPath);
        u.setBucketName(loginUser.getACCOUNTCONFIG().getBucketone());
        tem.add(u);
        new ImagesBulkUpload(this, tem, false, new ImagesBulkUpload.OnBulkImagesUploadListener() {

            @Override
            public void onImageUploadProgress(UploadBean image, long progress, long total) {
            }

            @Override
            public void onImageUploadSucceed(UploadBean image) {
            }

            @Override
            public void onImageUploadFailed(UploadBean image) {
                LogUtils.e("--", "图像上传失败原因：" );
                ToastUtil.getInstance().showToast(ActivityUserInfo.this, "图像上传失败", Toast.LENGTH_SHORT);
            }

            @Override
            public void onFinished(List<UploadBean> imagesUploadFailed) {
                showLoadingDialog();
                showLoadingDialog();
                MyHashMap map = new MyHashMap();
                map.put("headImg", headImageCloudKey);
                UserInfoUtils.toUpdateData(ActivityUserInfo.this, map, new UserInfoUtils.OnUpdateUserInfoBackListener() {
                    @Override
                    public void back(boolean issuccess, String msg) {
                        dissmissLoadingDialog();
                        if (issuccess) {//http://ozzptestimage1.oss-cn-shenzhen.aliyuncs.com//2103021484934144/b0c83dbd66a949f2a5b4368ff7ce84ab6092.jpeg
                            ToastUtil.getInstance().showToast(ActivityUserInfo.this, "保存成功");
                            UserInfoUtils.getNetLoginUser(ActivityUserInfo.this, new UserInfoUtils.OnGetNetInfoBack() {
                                @Override
                                public void back(LoginUser info) {
                                    initData();
                                }
                            });
                        }
                    }
                });
            }
        }).upload(0.7f);
    }

}
